package com.lk.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lk.springboot.dao.GameMapper;
import com.lk.springboot.dao.ScoreMapper;
import com.lk.springboot.dao.UserMapper;
import com.lk.springboot.pojo.SmallPhoto;
import com.lk.springboot.pojo.Ticket;
import com.lk.springboot.pojo.USHave;
import com.lk.springboot.service.GameService;
import com.lk.springboot.service.PidUtilService;
import com.lk.springboot.utils.RandomUtil;
import com.lk.springboot.utils.UniversalUtil;
import com.lk.springboot.vo.GameSP;
import com.lk.springboot.vo.Result;
import com.lk.springboot.vo.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lk
 * @date 2020/1/10 0010 22:56
 */
@Service
public class GameServiceImpl implements GameService {

    @Autowired
    GameMapper gameMapper;
    @Autowired
    PidUtilService pidUtilService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ScoreMapper scoreMapper;

    static final int SECRET = 2020;

    @Override
    public void addPhoto(String u_id, String sp_id) {
        sp_id = UniversalUtil.reduceSecret(sp_id, SECRET); // 解密
        String s_id = gameMapper.getSitesBySp(sp_id);   //取出拼图对应的的站点id
        String p_id = userMapper.getPidBySP(sp_id); // 取出sp_id 对应的 p_id
        List<String> list = userMapper.getPidFromActive(u_id, 0);// 获取未激活的p_id列表**
        if (list.contains(p_id)) {
            userMapper.updateActive(u_id, p_id);//记录激活状态
        }
        USHave usHave = new USHave(u_id, s_id, sp_id);
        gameMapper.addPhoto(usHave);                    //插入碎片获得记录的表里
    }

    @Override
    public String giveSP(String u_id, int type) {
        RandomUtil randomUtil = new RandomUtil();
        Result result = new Result(ResultCode.SUCCESS);
        List<GameSP> spList = new ArrayList<>();
        int n;
        if (type == 0) {
            n = (int) (Math.random() * 10) % 3 + 1;//随机碎片个数
        } else {
            n = 1;//随机碎片个数
        }
        List<String> pidList = pidUtilService.getNoActiveRandomPid(u_id, n); // 概率性，可能获取用户未激活过的******
        List<String> rareList = randomUtil.randomGetRares(n);    // 稀有度控制【A B C D】
        //获取碎片列表
        for (int i = 0; i < n; i++) {
            GameSP theSiteSP = gameMapper.getSmallPhoto(pidList.get(i), rareList.get(i));
            String the_sp = UniversalUtil.addSecret(theSiteSP.getSp_id(), SECRET); // 加密
            theSiteSP.setSp_id(the_sp);                                            // 对sp_id加密
            spList.add(theSiteSP);//放到集合里面
        }
        if (type == 0) {
            result.setData(spList);
        } else {
            String sp_id = UniversalUtil.reduceSecret(spList.get(0).getSp_id(), SECRET);
            SmallPhoto smallPhoto = gameMapper.getSmallPhotoBySpId(sp_id);
            int sp_id_num = Integer.parseInt(sp_id.replace("sp", "")) % 4;
            if (sp_id_num == 0)
                sp_id_num = 4;
            smallPhoto.setName(scoreMapper.getSName(sp_id) + "0" + sp_id_num);
            result.setData(smallPhoto);
        }
        return JSON.toJSONString(result);
    }

    @Override
    public int addScore(String u_id, String gameType, int gameScore) {  //******规则未定，需要修改****************************
        int score_num = 0;
        if (gameScore >= 0 && gameScore < 5) {
            score_num = 0;
        } else if (gameType.equals("online")) {// 线上游戏（有限次数）
            if (gameScore >= 5 && gameScore < 20)
                score_num = 10;
            else if (gameScore >= 20 && gameScore < 50)
                score_num = 20;
            else if (gameScore >= 50 && gameScore < 60)
                score_num = 40;
            else
                score_num = 40 + (gameScore - 60) / 5;

        } else if (gameType.equals("offline")) { //线下游戏（无限次数）
            if (gameScore >= 5 && gameScore < 20)
                score_num = 3;
            else if (gameScore >= 20 && gameScore < 50)
                score_num = 10;
            else if (gameScore >= 50 && gameScore < 60)
                score_num = 20;
            else
                score_num = 30 + (gameScore - 60) / 5;

        }
        if (score_num > 0)
            gameMapper.signGame(u_id);
        gameMapper.addScore(u_id, score_num);
        return score_num;
    }

    @Override
    public String getMaxGameScore(String u_id) {
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(gameMapper.getMaxGameScore(u_id));
        return JSON.toJSONString(result);
    }

    @Override
    public boolean getIsRecordBreaking(String u_id, int gameScore) {
        if (gameScore > gameMapper.getMaxGameScore(u_id)) {  //破纪录
            gameMapper.updateMaxGameScore(u_id, gameScore);// 更新记录
            return true;
        } else { // 未 破纪录
            return false;
        }
    }

    @Override
    public void setNewGameUser(String u_id) {
        userMapper.setNewGameUser(u_id);
    }

    @Override
    public void prepareSP(String u_id) {
        RandomUtil randomUtil = new RandomUtil();
        List<String> pidList = pidUtilService.getNoActiveRandomPid(u_id, 1); // 概率性，可能获取用户未激活过的******
        List<String> rareList = randomUtil.randomGetRares(1);    // 稀有度控制【A B C D】
        GameSP theSiteSP = gameMapper.getSmallPhoto(pidList.get(0), rareList.get(0));
        gameMapper.prepareSP(theSiteSP.getSp_id());
    }

    @Override
    public Result getSP(String u_id) {
        Result result = new Result(ResultCode.SUCCESS);
        JSONObject jsonObject = new JSONObject();
        List<String> list = gameMapper.getSp();
        String sp_id = " ";
        if (list != null && list.size() != 0) {
            sp_id = list.get(0);
            SmallPhoto smallPhoto = gameMapper.getSmallPhotoBySpId(sp_id);
            int sp_id_num = Integer.parseInt(sp_id.replace("sp", "")) % 4;
            if (sp_id_num == 0)
                sp_id_num = 4;
            smallPhoto.setName(scoreMapper.getSName(sp_id) + "0" + sp_id_num);
            gameMapper.clearSP();
            jsonObject.put("type","photo");
            jsonObject.put("photo",smallPhoto);
            result.setData(jsonObject);
        }else {
            result.setData("Nothing");
        }
        return result;
    }

    @Override
    public Result getTicket(String u_id) {
        Result result = new Result(ResultCode.SUCCESS);
        Ticket ticket = gameMapper.getTicket(1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","ticket");
        jsonObject.put("ticket",ticket);
        result.setData(jsonObject);
        return result;
    }

    @Override
    public Result writeMsg(String u_id, String msg) {
        Result result;
        try{
            gameMapper.insertMsg(msg);
            result = new Result(ResultCode.SUCCESS);
            result.setData("留言发送成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new Result(ResultCode.UNEXPECTED_ERROR);
            result.setData("留言未发成功");
        }
        return result;
    }

    @Override
    public List<String> readMsg(String u_id) {
        return gameMapper.getAllMsg();
    }


}
